package org.example.kafka.commit;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.example.kafka.common.CommonConstant;
import org.example.kafka.common.KafkaConstants;
import sun.awt.IconInfo;

import java.util.Collections;
import java.util.Properties;

/**
 * 手动提交当偏移量，生产者使用ProducerCommit
 */
public class CommitSync {
    public static void main(String[] args) {
        // 消息的消费者
        Properties properties = KafkaConstants.consumerConfig("CommitSync", StringDeserializer.class,StringDeserializer.class);

        // 取消手动提交
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);
        // 创建消费者
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String, String>(properties);
        try{
            // 消费者开始订阅主题
            consumer.subscribe(Collections.singletonList(CommonConstant.CONSUMER_COMMIT_TOPIC));
            while (true){
                // 500毫秒去拉取一次数据
                ConsumerRecords<String,String> records = consumer.poll(500);
                for (ConsumerRecord<String,String> record:records){
                    System.out.println(String.format(
                            "主题：%s，分区：%d，偏移量：%d，key：%s，value：%s",
                            record.topic(),record.partition(),record.offset(),
                            record.key(),record.value()));
                    //do our work
                }
                //开始事务
                //读业务写数据库-
                //偏移量写入数据库
                //提交
                consumer.commitSync();
            }
        }finally {
            consumer.close();
        }


    }
}
